package com.umxwe.kill.core.template.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.umxwe.kill.core.template.dao.BaseMapper;
import com.umxwe.kill.core.template.domain.PageQueryParams;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public abstract class AbstractBaseServiceImpl<T extends PageQueryParams> implements IBaseService<T> {
    protected abstract BaseMapper<T> getMapper();

    @Override
    public List<T> select(T t) {
        return getMapper().select(t);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public T insertSelective(T t) {
        getMapper().insertSelective(t);
        return t;
    }

    @Override
    public PageInfo<T> query(T t) {
        if (t.getPageNum() == null) {
            t.setPageNum(1);
        }
        if (t.getPageSize() == null) {
            t.setPageSize(10);
        }
        return PageHelper.startPage(t.getPageNum(), t.getPageSize()).count(t.isCount()).setOrderBy(t.getOrderBy()).doSelectPageInfo(
                () -> getMapper().select(t)
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public T updateByPrimaryKeySelective(T t) {
        getMapper().updateByPrimaryKeySelective(t);
        return t;
    }

    @Override
    public int deleteByPrimaryKey(Object id) {
        return getMapper().deleteByPrimaryKey(id);
    }

    @Override
    public T selectOne(T t) {
        List<T> list = getMapper().select(t);
        if (list == null || list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public T get(Object id) {
        return getMapper().selectByPrimaryKey(id);
    }

    @Override
    public long selectCount(T t) {
        return getMapper().selectCount(t);
    }

}
